//动态列表
const express = require('express');
const router = express.Router();
//导入连个内置模块
const path = require('path')
const fs = require('fs')
// 导入动态模型
const dynamicModel = require('../../model/dynamicModel')
// 用户模型
const uaerModel = require('../../model/uaerModel')
//消息通知
const messageModel = require('../../model/messageModel')
// 随机生成id
const get_id_string = require('../../utils/setId')
const random = require("../../utils/randomUser") //随机生成name方法

const {
    createUserDate
} = require('../../utils/createDate')
// 查询所有动态
router.post('/list', async function (req, res, next) {
    let body = req.body
    let dynamlcobj = await dynamicModel.find()
    await dynamicModel.find().sort({
        createDate: -1
    }).limit(body.pageSize).skip((body.pageIndex - 1) * body.pageSize).then((data) => {
        res.send({
            code: 200,
            success: true,
            msg: "列表查询成功",
            data,
            total: dynamlcobj.length
        })
    }).catch((err) => {
        res.send({
            code: 500,
            success: false,
            msg: "列表查询失败",
            data: err
        })
    });
})
// 创建发布动态
router.post('/create', async function (req, res, next) {
    let body = {
        createUserId: req.body.createUserId,
        dynamicText: req.body.dynamicText,
        dynamicImage: req.body.dynamicImage
    }
    const user = await uaerModel.find({ userId: req.body.createUserId })
    const dynamicall = await dynamicModel.find()
    body.id = get_id_string() + (dynamicall.length + 1)
    body.createUser = user[0].userName
    body.createPhone = user[0].phone
    body.createUserimg = user[0].userImg
    body.createUserrole = user[0].Administrator
    body.createDate = createUserDate()


    await dynamicModel.create(body).then((data) => {
        res.send({
            code: 200,
            success: true,
            msg: "发布成功",
            data,
        })
    }).catch((err) => {
        res.send({
            code: 500,
            success: false,
            msg: "发布失败",
            data: err
        })
    });
})

var multer = require("multer");
var upload = multer({ dest: 'img_Dynamic/' }) //文件目录

//上传文件
router.post('/uploads', upload.single('files'), async function (req, res, next) {
    //重新命名，避免重复
    let imgUrl = await random('动态-', 5) + '-' + req.file.originalname
    let oldPath = req.file.path;
    let newPath = 'img_Dynamic/' + imgUrl;

    fs.renameSync(oldPath, newPath)
    let CObj = {
        code: 200,
        msg: "上传成功",
        success: true,
        imgUrl: '/' + imgUrl
    }
    res.send(CObj)
});

//删除图片
router.post('/deleteImg', async function (req, res, next) {
    await fs.unlinkSync('./img_Dynamic/' + req.body.url)
    res.send({
        code: 200,
        success: true,
        msg: "图片已删除",
    })
})

//用户点赞
router.post('/give', async function (req, res, next) {
    let body = {
        userId: req.body.userId,
        userName: req.body.userName
    }
    // 消息通知创建对象
    const message = await messageModel.find()
    const userobj = await uaerModel.find({ userId: req.body.userId })
    const give = await dynamicModel.find({ id: req.body.id })
    let messageBody = {
        id: get_id_string() + (message.length + 1),//id
        byUserId: req.body.tongzhiuserid,//被通知的用户id
        otherUserId: req.body.userId,//通知你的用户id
        give: give[0],
        isGive: 0,
        date: createUserDate(),
        otherUserName: userobj[0].userName,
        otherUserImg: userobj[0].userImg,
    }
    await dynamicModel.updateOne({
        id: req.body.id
    }, {
        $push: {
            dynamicGive: body
        }
    }).then(async data => {
        // 消息通知
        if (req.body.tongzhiuserid !== req.body.userId) {
            await messageModel.create(messageBody)
        }
        res.send({
            code: 200,
            msg: "点赞成功",
            success: true,
        })
    }).catch((err) => {
        res.send({
            code: 500,
            success: false,
            msg: "点赞失败",
            data: err
        })
    });
})

// 查询动态详情
router.post('/listDetails', async function (req, res, next) {
    await dynamicModel.find({ id: req.body.id }).sort().then((data) => {
        res.send({
            code: 200,
            success: true,
            msg: "详情查询成功",
            data,
        })
    }).catch((err) => {
        res.send({
            code: 500,
            success: false,
            msg: "详情查询失败",
            data: err
        })
    });
})

//评论
router.post('/comment', async function (req, res, next) {
    let byUserId = ""
    let byUserName = ""
    let byUserImg = ""
    let byUserRoleId = ""
    let tongzhiuserid = ""
    if (req.body.byUserId == '' || req.body.byUserId == null || req.body.byUserId == undefined) {
        byUserId = ""
        byUserName = ""
        byUserImg = ""
        byUserRoleId = ""
        tongzhiuserid = req.body.tongzhiuserid
    } else {
        const Byuserobj = await uaerModel.find({ userId: req.body.byUserId })
        byUserId = req.body.byUserId
        byUserName = Byuserobj[0].userName
        byUserImg = Byuserobj[0].userImg
        byUserRoleId = Byuserobj[0].Administrator
        tongzhiuserid = req.body.byUserId
    }
    const userobj = await uaerModel.find({ userId: req.body.userId })
    let body = {
        userId: req.body.userId,//回复人id
        byUserId: byUserId,//被回复人id
        contentText: req.body.contentText,
        contentImg: req.body.contentImg,
        contentDate: createUserDate()
    }
    body.UserName = userobj[0].userName//回复人用户名
    body.UserImg = userobj[0].userImg//回复人头像
    body.UserRoleId = userobj[0].Administrator//回复人角色
    body.byUserName = byUserName//被回复人用户名
    body.byUserImg = byUserImg//被回复人头像
    body.byUserRoleId = byUserRoleId//被回复人角色
    // 消息通知创建对象
    const message = await messageModel.find()
    const dynamicobj = await dynamicModel.find({ id: req.body.id })
    let messageBody = {
        id: get_id_string() + (message.length + 1),//id
        byUserId: tongzhiuserid,//被通知的用户id
        otherUserId: req.body.userId,//通知你的用户id
        dynamic: dynamicobj[0],
        isDynamic: 0,
        date: createUserDate(),
        otherUserName: userobj[0].userName,
        otherUserImg: userobj[0].userImg,
        dynamicContent: req.body.contentText
    }
    await dynamicModel.updateOne({
        id: req.body.id
    }, {
        $push: {
            dynamiccomment: body
        }
    }).then(async data => {
        // 消息通知
        if (tongzhiuserid !== req.body.userId) {
            await messageModel.create(messageBody)
        }
        res.send({
            code: 200,
            msg: "评论成功",
            success: true,
        })
    }).catch((err) => {
        res.send({
            code: 500,
            success: false,
            msg: "评论失败",
            data: err
        })
    });
})
module.exports = router;